package org.nifi.processors.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import java.util.Objects;

/**
 * JSON工具类，基于Jackson实现
 */
@UtilityClass
public class JsonUtils {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 实体序列化成Json对象
     */
    @SneakyThrows
    public String serializeJson( Object object) {
        if (Objects.isNull(object)) {
            return null;
        }
        return OBJECT_MAPPER.writeValueAsString(object);
    }

    /**
     * Json对象反序列化实体
     */
    @SneakyThrows
    public <T> T deserializeJson(String jsonString, Class<T> clazz) {
        Assert.notNull(clazz, () -> new IllegalArgumentException("Class参数不能为空"));
        if (StrUtil.isBlank(jsonString)) {
            return null;
        }
        return OBJECT_MAPPER.readValue(jsonString, clazz);
    }

    /**
     * Json对象反序列化实体
     */
    @SneakyThrows
    public <T> T deserializeJson(String jsonString, TypeReference<T> reference) {
        Assert.notNull(reference, () -> new IllegalArgumentException("TypeReference参数不能为空"));
        if (StrUtil.isBlank(jsonString)) {
            return null;
        }
        return OBJECT_MAPPER.readValue(jsonString, reference);
    }

}
